import { ENUM_TON_NOTCH, ExtOrder, TonOrder, TonOrderJoinLs, TonOrderJoinLsKey, WithStockTotal } from "qqlx-core";

import { toNumber, toString } from "@lib/com.verify";
import { getIntroUpdater } from "@/data-base";
import { doNotchMerge } from "@/river/data-river-ton-tpl";
import { doBitsToDecimal, doDecimalToBits } from "@lib/com.binary";

export function getOrderCopy(order: ExtOrder) {
  return {
    ...getIntroUpdater(order),
    contractSide: order.contractSide.replace(/\s+/g, ""),
    contractSideOp: order.contractSideOp.replace(/\s+/g, ""),
    contractTime: toNumber(order.contractTime).toString(),
    contractBrief: order.contractBrief.replace(/\s+/g, ""),

    code: toString(order.code).replace(/\s+/g, ""),
    amount: Math.abs(toNumber(order.amount)),
    amountTax: Math.abs(toNumber(order.amountTax)),
  };
}

/** 帮助订单，补充库存信息 */
export function formatTonOrderStock<T>(orders: (T & TonOrder)[]): (T & TonOrder & WithStockTotal)[] {
  return orders.map((order) => {
    const calcCount = doNotchMerge((order.joinOrderStockList || []).filter((c) => c.key === "count"));
    const calcTon = doNotchMerge((order.joinOrderStockList || []).filter((c) => c.key === "ton"));

    return {
      ...order,
      //
      withInOutCountTotal: calcCount.map.get(ENUM_TON_NOTCH.IN_OUT)?.total || "0",
      withInOutTonTotal: calcTon.map.get(ENUM_TON_NOTCH.IN_OUT)?.total || "0",
      //
      withNotInCountTotal: calcCount.map.get(ENUM_TON_NOTCH.NOT_IN)?.total || "0",
      withNotInTonTotal: calcTon.map.get(ENUM_TON_NOTCH.NOT_IN)?.total || "0",
      //
      withNotProcessCountTotal: calcCount.map.get(ENUM_TON_NOTCH.NOT_PROCESS)?.total || "0",
      withNotProcessTonTotal: calcTon.map.get(ENUM_TON_NOTCH.NOT_PROCESS)?.total || "0",
      //
      withNotOutCountTotal: calcCount.map.get(ENUM_TON_NOTCH.NOT_OUT)?.total || "0",
      withNotOutTonTotal: calcTon.map.get(ENUM_TON_NOTCH.NOT_OUT)?.total || "0",
    };
  });
}

/** 将订单的查询对象，转换成二进制字符串 */
export function getTonOrderJoinDecimal(option: Partial<Record<TonOrderJoinLsKey, true>>) {
  const value = doDecimalToBits(0, TonOrderJoinLs.length);
  const bits = value.bits.split("");

  for (const key in option) {
    const index = TonOrderJoinLs.findIndex((k) => k === key);
    if (index > -1) bits[index] = "1";
  }
  return doBitsToDecimal(bits.join("")).decimal;
}

/** 将二进制字符串，转换成订单的查询对象 */
export function getTonOrderJoinRecord(decimal: number) {
  const value = doDecimalToBits(decimal, TonOrderJoinLs.length);
  const bits = value.bits.split("");

  const record: Partial<Record<TonOrderJoinLsKey, true>> = {};
  for (const index in bits) {
    const key = TonOrderJoinLs[index];
    if (bits[index] === "1") record[key] = true;
  }
  return record;
}
